package com.nbcio.modules.erp.cart.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nbcio.modules.erp.cart.entity.Cart;
import com.nbcio.modules.erp.cart.entity.CartItems;
import com.nbcio.modules.erp.cart.entity.SysUser;
import com.nbcio.modules.erp.cart.mapper.CartMapper;
import com.nbcio.modules.erp.cart.service.CartItemsService;
import com.nbcio.modules.erp.cart.service.CartService;
import com.nbcio.modules.erp.goods.entity.ErpGoods;
import com.nbcio.modules.erp.goods.entity.ErpGoodsCategory;
import com.nbcio.modules.erp.goods.entity.ErpGoodsPrice;
import com.nbcio.modules.erp.goods.service.IErpGoodsCategoryService;
import com.nbcio.modules.erp.goods.service.IErpGoodsPriceService;
import com.nbcio.modules.erp.goods.service.IErpGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;

/**
* @author 31955
* @description 针对表【cart】的数据库操作Service实现
* @createDate 2024-04-10 14:42:42
*/
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart>
    implements CartService{

    @Autowired
    private CartItemsService cartItemsService;

    @Autowired
    private IErpGoodsService erpGoodsService;

    @Autowired
    private IErpGoodsCategoryService erpGoodsCategoryService;

    @Autowired
    private IErpGoodsPriceService erpGoodsPriceService;


    /**
     * 添加购物车
     * @param map
     */
    @Override
    @Transactional
    public void saveMain(Map<String,Object> map) {

        Map main = JSON.parseObject(JSON.toJSONString(map.get("main")), Map.class);
        List<Map> subList = JSON.parseArray(JSON.toJSONString(map.get("sub")), Map.class);

        String user_id = main.get("user_id").toString();

        LambdaQueryWrapper<Cart> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, user_id);
        Cart one = getOne(wrapper);
        //主表赋值
        Cart cart = new Cart();
        if (one == null){
            cart.setId(RandomUtil.randomString(32));
            cart.setUserId(user_id);

            CartItems cartItems =  new CartItems();
            Map sub = subList.get(0);
            //子表赋值
            cartItems.setId(RandomUtil.randomString(32));
            cartItems.setCartId(cart.getId());
            getAddData(cartItems, sub);

            save(cart);
            cartItemsService.save(cartItems);
        }else {
            CartItems cartItems =  new CartItems();
            String id = one.getId();
            //子表赋值
            Map sub = subList.get(0);

            //根据商品去查购物车明细
            LambdaQueryWrapper<CartItems> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CartItems::getCartId, id)
                    .eq(CartItems::getProductId,sub.get("product_id").toString());
            CartItems items = cartItemsService.getOne(queryWrapper);
            if (items != null) {
                items.setQuantity(BigDecimal.valueOf(Double.parseDouble(sub.get("quantity").toString())).add(items.getQuantity()));
                cartItemsService.updateById(items);
            }else {
                cartItems.setId(RandomUtil.randomString(32));
                cartItems.setCartId(id);
                getAddData(cartItems, sub);
                cartItemsService.save(cartItems);
            }
        }
    }

    /**
     * 子表新增数据组装
     * @param cartItems
     * @param sub
     */
    private void getAddData(CartItems cartItems, Map sub) {
        cartItems.setProductId(sub.get("product_id").toString());
        cartItems.setProductName(sub.get("name").toString());

        LambdaQueryWrapper<ErpGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ErpGoods::getId, sub.get("product_id").toString());
        ErpGoods erpGoods = erpGoodsService.getOne(wrapper);
        if (erpGoods == null) {
            cartItems.setProductClassId("");
            cartItems.setProductClassName("");
            cartItems.setNgtorigprice(BigDecimal.ZERO);
            cartItems.setNgtorigtaxprice(BigDecimal.ZERO);
            cartItems.setNtax(BigDecimal.ZERO);
            cartItems.setNtaxrate(BigDecimal.ZERO);
        }

        LambdaQueryWrapper<ErpGoodsPrice> priceWrapper = new LambdaQueryWrapper<>();
        priceWrapper.eq(ErpGoodsPrice::getId,erpGoods.getId());
        ErpGoodsPrice erpGoodsPrice = erpGoodsPriceService.getOne(priceWrapper);
        if (erpGoodsPrice == null) {
            cartItems.setNgtorigprice(BigDecimal.ZERO);//无税单价
            cartItems.setNgtorigtaxprice(BigDecimal.ZERO);//含税单价
        }else {
            cartItems.setNgtorigprice(erpGoodsPrice.getSale());//无税单价
            cartItems.setNgtorigtaxprice(erpGoodsPrice.getPurchase());//含税单价
        }

        cartItems.setProductClassId(erpGoods.getCategoryId());
        LambdaQueryWrapper<ErpGoodsCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ErpGoodsCategory::getId, erpGoods.getCategoryId());
        ErpGoodsCategory erpGoodsCategory = erpGoodsCategoryService.getOne(queryWrapper);
        cartItems.setProductClassName(erpGoodsCategory.getName());
        cartItems.setNtax(erpGoods.getSaleTaxRate());//税额
        cartItems.setNtaxrate(erpGoods.getTaxRate());//税率
        cartItems.setImg(sub.get("img").toString());
        cartItems.setQuantity(BigDecimal.valueOf(Double.parseDouble(sub.get("quantity").toString())));
        cartItems.setPrice(BigDecimal.valueOf(Double.parseDouble(sub.get("price").toString())));
    }


    /**
     * 查询购物车
     * @param mainId
     * @return
     */
    @Override
    public Map<String, Object> queryMain(String mainId) {

        Map<String,Object> map = new HashMap<>();
        LambdaQueryWrapper<Cart> cartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        cartLambdaQueryWrapper.eq(Cart::getUserId, mainId);
        Cart cart = getOne(cartLambdaQueryWrapper);
        if (cart != null) {
            List<CartItems> cartItemsList = cartItemsService.queryByMainId(cart.getId());

            map.put("main", cart);
            map.put("sub", cartItemsList);
        }else {
            map.put("main", new Cart());
            map.put("sub", new ArrayList<>());
        }

        return map;
    }

    /**
     * 修改购物车明细
     * @param map
     */
    @Override
    public void updateMain(Map<String,Object> map) {

        String id = map.get("id").toString();
        int num = Integer.parseInt(map.get("num").toString());
        CartItems cartItems = cartItemsService.getById(id);
        cartItems.setQuantity(BigDecimal.valueOf(num));
        cartItemsService.updateById(cartItems);
    }

    /**
     * 删除购物车明细
     * @param map
     */
    @Override
    public void deleteMain(Map<String,Object> map) {

        String id = map.get("id").toString();
        String mainId = map.get("main_id").toString();
        List<CartItems> cartItemsList = cartItemsService.queryByMainId(mainId);
        //只剩最后一个了
        if (cartItemsList.size()==1){
            removeById(mainId);
        }
        cartItemsService.removeById(id);
    }

    /**
     * 批量删除购物车明细
     * @param map
     */
    @Override
    public void deleteBatchMain(Map<String,Object> map) {

        List<String> idList = JSON.parseArray(JSON.toJSONString(map.get("id")), String.class);

        String mainId = map.get("main_id").toString();
        List<CartItems> cartItemsList = cartItemsService.queryByMainId(mainId);
        //只剩最后一个了
        if (cartItemsList.size()==idList.size()){
            removeById(mainId);
        }

        LambdaQueryWrapper<CartItems> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(CartItems::getId, idList);
        List<CartItems> queryList = cartItemsService.list(wrapper);

        cartItemsService.removeBatchByIds(queryList);
    }
}




